package com.chat.service;

import com.chat.Local;
import com.chat.common.ChatMsg;
import com.chat.common.Message;
import com.chat.common.MessageType;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;

public class SendFileThread extends Thread{
    public FileInputStream fis=null;
    public String filename;
    public String address;
    public File file;

    public void set(File file,String address){
        try {
            fis=new FileInputStream(file);
            this.file=file;
            this.address=address;
            this.filename=file.getName();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            byte[] b=new byte[1024*1024];
            int count=0;
            int count1= (int) (file.length()/(1024*1024));
            int n;
            int count2=(int) (file.length()%(1024*1024));
            Message msg=new Message();
            ClientConnectServerThread clientConnectServerThread=ManageClientConnectServerThread.getClientConnectServerThread(Local.user.getUsername());
            while(count1!=0&&(n=fis.read(b))!=-1){
                ChatMsg cm=new ChatMsg();
                cm.setFile(b);
                cm.setCount(++count);
                cm.setSenderid(Local.user.getUsername());
                msg.setData(cm);
                msg.setMesType(MessageType.MESSAGE_PARTIAL_FILE);
                clientConnectServerThread.send(msg);
                if(count1==(count))break;
            }
            if(count2!=0){
                byte[] c=new byte[count2];
                while((n=fis.read(c))!=-1){
                     ChatMsg cm=new ChatMsg();
                     cm.setFile(c);
                     cm.setCount(++count);
                    cm.setSenderid(Local.user.getUsername());
                    msg.setData(cm);
                    msg.setMesType(MessageType.MESSAGE_PARTIAL_FILE);
                    clientConnectServerThread.send(msg);
                }
            }
            System.out.println("获取成功");
               ChatMsg cm=new ChatMsg();
               cm.setSenderid(Local.user.getUsername());
               cm.setFilename(filename);
               cm.setCount(count);
               cm.setAddress(address);
               msg.setData(cm);
               msg.setMesType(MessageType.MESSAGE_MERGE_FILE);
               clientConnectServerThread.send(msg);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
